<template>
  <div class="home-container">
    <van-nav-bar fixed>
      <template #right>
        <van-icon
          name="search"
          size="18"
          v-on:click="$router.push('/search')"
        />
      </template>
    </van-nav-bar>

    <van-tabs
      v-model="active"
      sticky
      offset-top="46"
      :before-change="beforeTabsChange"
      @change="onTabsChange"
    >
      <van-tab
        v-for="(item, index) in userChannel"
        :title="item.name"
        :key="index"
      >
        <art-list :channel-id="item.id"></art-list>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>
import { getUserChannelAPI } from '@/api/homeAPI.js'
import ArtList from '@/components/ArtList/ArtList.vue'
// 定义一个对象，键是索引，值是高度；格式 { 0: 100, 1: 233 }
const indexToTop = {}
export default {
  name: 'Home',
  data() {
    return {
      active: 0,
      userChannel: []
    }
  },

  components: {
    ArtList
  },

  computed: {},

  mounted() {
    this.getUserChannel()
  },

  methods: {
    async getUserChannel() {
      const { data: res } = await getUserChannelAPI()
      if (res.message === 'OK') {
        this.userChannel = res.data.channels
      }
    },
    beforeTabsChange() {
      console.log('beforeTabsChange')
      indexToTop[this.active] = window.scrollY
      console.log('indexToTop:', indexToTop)
      return true
    },
    onTabsChange() {
      window.scrollTo(0, indexToTop[this.active] || 0)
    }
  }
}
</script>
<style lang="less" scoped>
// 组件外层容器的样式
.home-container {
  padding-top: 92px;
  padding-bottom: 100px;
}

/deep/ .van-tabs__line {
  background-color: blue;
}

// logo 样式
.logo {
  height: 80%;
}

// 为 tabs 容器设置右 padding
/deep/ .van-tabs__wrap {
  padding-right: 36px;
  background-color: white;
}

// 频道管理小图标的定位
.plus {
  position: fixed;
  top: 58px;
  right: 10px;
  z-index: 999;
}

.van-popup,
.popup-container {
  background-color: transparent;
  height: 100%;
  width: 100%;
}

.popup-container {
  display: flex;
  flex-direction: column;
}

.pop-body {
  flex: 1;
  overflow: scroll;
  padding: 8px;
  background-color: white;
}

.my-channel-box,
.more-channel-box {
  .channel-title {
    display: flex;
    justify-content: space-between;
    font-size: 14px;
    line-height: 28px;
    padding: 0 6px;
    .title-bold {
      font-weight: bold;
    }
    .title-gray {
      color: gray;
      font-size: 12px;
    }
  }
}

.btn-edit {
  border: 1px solid #a3a2a2;
  padding: 0 10px;
  line-height: 20px;
  height: 20px;
  border-radius: 6px;
  font-size: 12px;
}

.channel-item {
  font-size: 12px;
  text-align: center;
  line-height: 36px;
  background-color: #fafafa;
  margin: 6px;
}

.cross-badge {
  position: absolute;
  right: -3px;
  top: 0;
  border: none;
}

.sp-line {
  margin: 10px 0 20px 0;
}
</style>
